from .shoutcut_import import *
from app.controller.validate.product_validate import ProductPostValidate, ProductGetValidate

from app.model.product_model import ProductModel
from app.model.store_model import StoreModel
from app.model.user_model import UserModel
from app.model.category_model import CategoryModel
from app.model.product_category_model import ProductCategoryModel

bp = V1BluePoint('product', __name__, url_prefix='')


@bp.route('product', methods=['POST'])
@user_require
@validate_form(ProductPostValidate)
def post_product():
    """增加商品"""
    uid = g.uid
    user = UserModel.query.filter_by(id=uid).first()

    if not user:
        return error_json(ResponseCode.INTERNAL_SERVER_ERROR, '用户异常')
    if not user.store_id:
        return error_json(ResponseCode.OPERATOR_ERROR, '用户不是商户')
    store = StoreModel.query.filter_by(id=user.store_id).first()
    if not store:
        return error_json(ResponseCode.INTERNAL_SERVER_ERROR, '商户信息异常')
    if store.status != constant.StoreStatus.RUNNING:
        return error_json(ResponseCode.OPERATOR_ERROR, '商户未在正常营业')

    product = ProductModel(request.json, store_id=store.id)
    sqla_db.session.add(product)
    sqla_db.session.commit()
    if not product.id:
        return error_json(ResponseCode.INTERNAL_SERVER_ERROR, '保存商品失败')
    cates_id = request.json.get('categorys_id', '')
    cates_id = cates_id.split('|')
    for cate_id in cates_id:
        prod_cate = ProductCategoryModel(product_id=product.id, category_id=cate_id)
        sqla_db.session.add(prod_cate)
    sqla_db.session.commit()
    return success_json({"id": product.id})


@bp.route('product', methods=['GET'])
@user_require
@validate_form(ProductGetValidate)
def get_product():
    """获取商品"""
    product_id = request.args.get('id')
    if product_id:
        product = ProductModel.query.filter_by(id=product_id).first()
        if not product:
            return error_json(ResponseCode.RESOURCE_NOT_FOUND, '指定商品ID不存在')
        product = product.to_dict()
        return success_json(product)
    category = request.args.get('cg')
    size = request.args.get('s', current_app.config.get('APP_DEFAULT_PAGE_SIZE', 16))
    page = request.args.get('p', 1)
    page = int(page)
    size = int(size)
    # select * from tb_product left join tb_product_category on tb_product.id=tb_product_category.product_id where category_id=2
    # sqlalchemy 自动过滤重复
    sql = ProductModel.query \
        .join(ProductCategoryModel, ProductCategoryModel.product_id == ProductModel.id) \
        .filter(ProductCategoryModel.category_id == category) \
        .order_by(ProductModel.id) \
        .limit(size).offset((page-1)*size)
    products = sql.all()
    products = ProductModel.to_list(products)
    return success_json(products, count=len(products))
